import { _decorator, Component, Node, Prefab, Input, __private, EventTouch, Sprite, math, v3, tween, RigidBody2D, v2, BoxCollider2D, Contact2DType, CCInteger, SpriteFrame, assetManager, ImageAsset, loader, Texture2D, Asset, Animation, director, Label, Button } from 'cc';
import { DataManager } from '../Public/DataManager';
import { PoolManager } from '../Public/PoolManager';
import { PublicFn } from '../Public/PublicFn';
const { ccclass, property } = _decorator;
@ccclass('play')
export class play extends Component {
    /**图标父节点 */
    @property({ displayName: '图标父节点', type: Node })
    itemsNode: Node = null;
    /**图标预制体 */
    @property({ displayName: '图标预制体', type: Prefab })
    item: Prefab = null;
    /**图标预制体 */
    @property({ displayName: '根图标预制体', type: Prefab })
    RootItem: Prefab = null;
    /**补给节点 */
    @property({ displayName: '补给节点', type: Node })
    supplyNode: Node = null;
    /**箱子节点 */
    @property({ displayName: '箱子节点', type: Node })
    box: Node = null;
    /**汽车节点 */
    @property({ displayName: '汽车节点', type: Node })
    car: Node = null;
    /**堆叠高度 */
    @property({ displayName: '堆叠高度', type: CCInteger })
    itemsHeight: number = 40;
    /**汽车运动总时间 */
    @property({ displayName: '汽车运动总时间', type: CCInteger })
    carMoveTime: number = 4;
    @property({ displayName: '设置', type: Node })
    setting: Node = null;
    @property({ displayName: '道具', type: Node })
    prop: Node = null;
    @property({ displayName: '胜利', type: Node })
    win: Node = null;
    @property({ displayName: '道具栏', type: Node })
    btns: Node = null;
    @property({ displayName: '掉落物父节点', type: Node })
    items: Node = null;
    @property([Label])
    propNum:Label[]=[];
    /**图案对比队列 */
    itemQueue: Node[] = [];
    /**图片生成数据 */
    randomArr: number[][] = [];
    /**是否使用上下变换道具 */
    isChange: boolean = false;
    /**不能触发点击事件 */
    NotClick: boolean = false;
    /**是否在补货 */
    isSupply: boolean = false;
    isLoad: boolean = true;
    isNext: boolean = false;
    
    start() {
        this.initData();
        this.btns.children[0].on(Input.EventType.TOUCH_START, this.useChange, this);
        this.btns.children[1].on(Input.EventType.TOUCH_START, this.useSupply, this);
        this.btns.children[2].on(Input.EventType.TOUCH_START, this.useRandom, this);
        this.btns.children[3].on(Input.EventType.TOUCH_START, this.OpenSetting, this);
    }
    /**
     * 图案点击与销毁
     * @param e 触摸的对象
     * @returns 
     */
    selectItem(e: EventTouch) {
        console.log('e.target :>> ', e.target);
        // console.log('this.NotClick :>> ', this.NotClick);
        //处于不能点击状态则返回
        if (this.NotClick) {
            return;
        }
        //如果不是最顶部的图案则不给选取
        if ((e.target.getSiblingIndex() !== e.target.parent.children.length - 1) && (!e.target[`Supply`])) {
            return;
        }
        //如果使用了上下交换道具则直接交换效果
        console.log('this.isChange :>> ', this.isChange);
        if (this.isChange) {
            return;
        }
        //搜索对比队列中是否有当前触摸的对象
        const index = this.itemQueue.findIndex((ele) => ele === e.target);
        //如果搜索到则进行选择取消
        if (index > -1) {
            e.target.children[0].active = false;
            this.itemQueue.splice(index, 1);
        }
        //没有则添加到对比队列中
        else {
            e.target.children[0].active = true;
            this.itemQueue.push(e.target);
            //当队列有3个图案时进行判断
            if (this.itemQueue.length >= 3) {
                const judge = (this.itemQueue[0].name === this.itemQueue[1].name) && (this.itemQueue[1].name === this.itemQueue[2].name);
                let isGet = 0;
                //都相同进行消除
                if (judge) {
                    this.itemQueue.forEach((e) => {
                        const num = e.parent.getSiblingIndex();
                        const Ani = e.getComponent(Animation);
                        Ani.play();
                        Ani.on(Animation.EventType.FINISHED, () => {
                            e.children[0].active = false;
                            if (!e[`Supply`]) {
                                PoolManager.Instance.putNode(e);
                                this.randomArr[num].splice(this.randomArr[num].length - 1, 1);
                            }
                            else {
                                PoolManager.Instance.putNode(e, 'supply');
                            }
                            Ani.off(Animation.EventType.FINISHED);
                            this.MoveSupplyItem();
                            if ((++isGet) >= 3) {
                                this.CheckOutcome();
                            }
                        })

                        // else {
                        // }
                        e.off(Input.EventType.TOUCH_START);
                    });
                    this.itemQueue = [];
                }
                //否则进行取消操作
                else {
                    this.scheduleOnce(() => {
                        this.itemQueue.forEach((e) => {
                            e.children[0].active = false;
                        });
                        this.itemQueue = [];
                    }, 0.1);
                }

            }
        }
    }
    /**图案补给 */
    SupplyItem() {
        const { supplyNode } = this
        const { materialsId, materials } = DataManager.Instance
        const len = supplyNode.children.length;
        for (let i = 0; i < 5 - len; i++) {
            const num = math.randomRangeInt(0, materialsId.length);
            const node = PoolManager.Instance.getNode(this.item, supplyNode, 'supply');
            node.on(Input.EventType.TOUCH_START, this.selectItem, this);
            node[`Supply`] = true;
            node.setPosition(0, (-311 + 157 * (len + i)) + 800);
            node.name = materialsId[num] ? materialsId[num] : `null`;
            node.getComponent(Sprite).spriteFrame = materials[materialsId[num]];
            // PublicFn.Instance.changeImg(`ItemIcon/${node.name}`, );
            tween(node).to(0.5, { position: v3(0, (-311 + 157 * (len + i))) }).start();
        }
    }
    /**
     * 上下图案交换
     * @param node 要进行变换的节点
     * @returns 
     */
    ChangeItem(node: Node) {
        //若是补货节点或不能点击则不执行效果
        if (node[`Supply`] || this.NotClick) {
            this.isChange = false;
            return;
        }
        else {
            //自身索引
            const index = node.parent.getSiblingIndex();
            //如果底下的节点不存在时返回
            if (!index) {
                this.isChange = false;
                return;
            }
            //底下的节点
            const preNode = node.parent.children[node.getSiblingIndex() - 1];
            const parentNode = node.parent;
            const self = this;
            this.NotClick = true;
            const w1 = node.getPosition();
            const w2 = preNode.getPosition();
            const target = this.randomArr[index];
            const len = target.length;
            const id = target[len - 1];
            target[len - 1] = target[len - 2];
            target[len - 2] = id;
            tween(preNode).parallel(tween(preNode).by(0.25, { position: v3(0, -50) }, {
                onComplete() {
                    preNode.setSiblingIndex(parentNode.children.length - 1);
                },
            }).by(0.25, { position: v3(0, 50, 1) },).start(),
                tween(node).by(0.25, { position: v3(0, 50) }).by(0.25, { position: v3(0, -50) }, {
                    onComplete() {
                        node.setPosition(w2);
                        preNode.setPosition(w1);
                        setTimeout(() => {
                            node.getComponent(Sprite).spriteFrame = DataManager.Instance.materials[target[len - 1]];
                            preNode.getComponent(Sprite).spriteFrame = DataManager.Instance.materials[target[len - 2]];
                            node.setPosition(w1);
                            preNode.setPosition(w2);
                            node.setSiblingIndex(parentNode.children.length - 1);
                            self.NotClick = false;
                            self.isChange = false;
                        }, 10);
                    }
                }).start()
            ).start();
            node.name = `${target[len - 1]}`;
            preNode.name = `${target[len - 2]}`;

        }
    }
    /**使用上下交替道具 */
    useChange() {
        if (this.isLoad) {
            return;
        }
        tween(this.btns.children[0]).to(0.1, { scale: v3(0.6, 0.6, 1) }).to(0.1, { scale: v3(0.5, 0.5, 1) }).start();
        if(DataManager.Instance.propArr[0])
        {
            if (DataManager.Instance.propArr[0][0]>0) {
                if(this.itemQueue.length==1)
                {
                    if(this.itemQueue[0][`Supply`])
                    {
                        return ;
                    }
                    this.isChange = true;
                    DataManager.Instance.propArr[0][0]--;
                    this.ChangeItem(this.itemQueue[0]);
                    this.updatePropNum();
                }
               
            }
            else {
                DataManager.Instance.curProp=0;
                this.prop.setPosition(0,0);
                this.prop.active=true;
            }
        }
        // this.randomArr=[];
        // this.CheckOutcome();
        // this.prop.active = true;

    }
    /**使用补货道具 */
    useSupply() {
        if (this.isLoad) {
            return;
        }
        tween(this.btns.children[1]).to(0.1, { scale: v3(0.6, 0.6, 1) }).to(0.1, { scale: v3(0.5, 0.5, 1) }).start();
        if(DataManager.Instance.propArr[1])
        {
            if (DataManager.Instance.propArr[1][0]>0) {
                if (this.isSupply || this.supplyNode.children.length >= 5) {
                    return;
                }
                DataManager.Instance.propArr[1][0]--;
                this.updatePropNum();
                this.scheduleOnce(() => this.CarMove(), 0.1);
            } else {
                DataManager.Instance.curProp=1;
                this.prop.setPosition(0,0);
                this.prop.active=true;
            }
        }
        // this.supplyNode.removeAllChildren();
        // this.prop.active = true;
    }
    /**使用随机打乱道具 */
    useRandom() {
        if (this.isLoad) {
            return;
        }
        tween(this.btns.children[2]).to(0.1, { scale: v3(0.6, 0.6, 1) }).to(0.1, { scale: v3(0.5, 0.5, 1) }).start();
        if(DataManager.Instance.propArr[2])
        {
            if (DataManager.Instance.propArr[2][0]>0) {
                DataManager.Instance.propArr[2][0]--;
                this.updatePropNum();
                this.scheduleOnce(() => this.ResetItem(), 0.1);
            } else {
                DataManager.Instance.curProp=2;
                this.prop.setPosition(0,0);
                this.prop.active=true;
            }
        }
        // this.prop.active = true;
    }
    update(deltaTime: number) {

    }
    /**随机打乱图案*/
    ResetItem() {
        const len = this.randomArr.length;
        for (let i = 0; i < len; i++) {
            if (this.randomArr[i]) {
                this.randomArr[i].sort(() => Math.random() - 0.5);
            }
        }
        // console.log('this.itemsNode.children :>> ', this.itemsNode.children);
        this.itemsNode.children.forEach((e, i) => {
            e.children.forEach((ele, ind) => {
                if (this.randomArr[i]) {
                    ele.getComponent(Sprite).spriteFrame = DataManager.Instance.materials[this.randomArr[i][ind]]
                    // PublicFn.Instance.changeImg(`ItemIcon/${}`, );
                    ele.name = `${this.randomArr[i][ind]}`;
                }
            })
        })
        console.log('this.itemsNode.children :>> ', this.itemsNode.children);

    }
    /**检查输赢 */
    CheckOutcome() {
        let sum = 0;
        this.randomArr.forEach((e) => {
            if (e instanceof Array) {
                // console.log('e', e)
                sum += e.length
            }
            return 0
        });
        console.log('sum :>> ', sum);
        if (!sum) {
            console.log('win');
            this.win.setPosition(0, 0);
            this.win.getChildByName(`Level`).getComponent(Label).string = `第${DataManager.Instance.curLevel + 1}关`;
            this.getWinReward();
        }
        else {
            console.log('sum', sum)
        }
    }
    /**创建牌局 */
    creatItems() {
        const len = this.randomArr.length;
        console.log('this.randomArr', this.randomArr)
        console.log('this.materials', DataManager.Instance.materials)
        for (let i = 0; i < len; i++) {
            const RootNode = PoolManager.Instance.getNode(this.RootItem, this.itemsNode, `RootItem`);
            RootNode.getComponent(Sprite).spriteFrame = null;
            // console.log('RootNode :>> ', RootNode);
            if (this.randomArr[i] instanceof Array) {
                // console.log('this.randomArr[i]',this.randomArr[i])
                const { length } = this.randomArr[i];
                this.randomArr[i].forEach((ele, i) => {
                    const node = PoolManager.Instance.getNode(this.item, RootNode);
                    node.setPosition(v3(0, this.itemsHeight * i / length));
                    node.on(Input.EventType.TOUCH_START, this.selectItem, this);
                    node.name = `${ele}`;
                    node.getComponent(Sprite).spriteFrame = DataManager.Instance.materials[ele];
                })
            }

        }
    }
    /**数据初始化 */
    initData() {
        const { token, LevelArr, curLevel } = DataManager.Instance
        let xhr = new XMLHttpRequest();
        console.log('LevelArr :>> ', LevelArr);
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/guan`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${token}`);
        xhr.send(`node_id=${LevelArr[curLevel][`node_id`]}`);
        console.log(`node_id=${LevelArr[curLevel][`node_id`]}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { data, code } = JSON.parse(xhr.response);
                console.log('xhr.response :>> ', JSON.parse(xhr.response));
                if (code == 200) {
                    const len = data.materials.length;
                    let loadNum = 0;
                    data.materials.forEach((e, i) => {
                        const str = e.materials_id;
                        const url = e.materials_img;
                        if (str && url) {
                            DataManager.Instance.materialsId.push(str);
                            const image = new Image();
                            image.src = e.materials_img;
                            image.onload = () => {
                                console.log('加载图片', loadNum);
                                const l = new ImageAsset(image);
                                const sp = SpriteFrame.createWithImage(l);
                                DataManager.Instance.materials[str] = sp;
                                if (len <= (++loadNum)) {
                                    this.creatItems();
                                    this.isLoad = false;
                                }
                            }
                        }
                    })
                    for (const key in data.map) {
                        const arr = key.split(".");
                        this.randomArr[Number(arr[0]) * 6 + Number(arr[1])] = data.map[key];
                    }
                    for (const key in data.prop) {
                        const dlt = data.prop[key];
                        if(dlt.prop_name.match('位置'))
                        {
                            DataManager.Instance.propArr[0]=[Number(dlt.initial_num), Number(dlt.obtainable_num)];
                        }
                         else if(dlt.prop_name.match('发牌'))
                        {
                            DataManager.Instance.propArr[1]=[Number(dlt.initial_num), Number(dlt.obtainable_num)];
                        }
                        else if(dlt.prop_name.match('打乱'))
                        {
                            DataManager.Instance.propArr[2]=[Number(dlt.initial_num), Number(dlt.obtainable_num)];
                        }
                    }
                    this.updatePropNum();
                }
            }
        }
    }
    /**获取通关奖励 */
    getWinReward() {
        const { token, LevelArr, curLevel, threadID } = DataManager.Instance
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/stageClear`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${token}`);
        if (LevelArr[curLevel + 1]) {
            xhr.send(`node_id=${LevelArr[curLevel][`node_id`]}`);
        }
        else {
            console.log('最后一关通关 :>> ', `node_id=${LevelArr[curLevel][`node_id`]}&clearance_id=${threadID}`);
            xhr.send(`node_id=${LevelArr[curLevel][`node_id`]}&clearance_id=${threadID}`);
        }
        console.log('node_id :>> ', LevelArr[curLevel][`node_id`]);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const {data}=JSON.parse(xhr.response);
                data.award.forEach((d,i)=>
                {
                    PublicFn.Instance.changeUrlImg(d.award_img,this.items.children[i].children[0].getComponent(Sprite));
                })
            }
        }
    }
    /**货物消除移动效果 */
    MoveSupplyItem() {
        this.supplyNode.children.forEach((e, i) => {
            tween(e).to(0.2, { position: v3(0, -311 + 157 * i) }).start();
        })
    }
    /**箱子滚动 */
    BoxRoll() {
        this.box.active = true;
        const Rigid = this.box.getComponent(RigidBody2D);
        const Collider = this.box.getComponent(BoxCollider2D);
        Rigid.type = 2;
        Rigid.applyForceToCenter(v2(-100), true);
        Rigid.angularVelocity = -15;
        Collider.on(Contact2DType.BEGIN_CONTACT, this.BoxCollider, this);
    }
    /**箱子碰撞事件 */
    BoxCollider() {
        const t = setTimeout(() => {
            this.box.setPosition(v3(0, 85));
            this.box.getComponent(RigidBody2D).type = 0;
            this.box.active = false;
            this.SupplyItem();
            clearTimeout(t);
        }, 1200);
    }
    /**汽车移动 */
    CarMove() {
        
        this.isSupply = true;
        const carPosition = this.car.getPosition();
        const self = this;
        let act = 0;
        tween(this.car).by(this.carMoveTime, { position: v3(Math.abs(carPosition.x) * 2) }, {
            onUpdate(target?, ratio?) {
                if (ratio > 0.5 && !(act & 1)) {
                    act += 1;
                    self.BoxRoll();
                }
                if (ratio > 0.4 && !(act & 1 << 1)) {
                    act += 1 << 1;
                    self.car.getComponentInChildren(Animation).play();
                }
            },
            onComplete() {
                self.car.setPosition(carPosition);
                self.isSupply = false;
            },
            easing: `sineInOut`
        }).start();
    }
    /**打开设置页 */
    OpenSetting() {
        tween(this.btns.children[3]).to(0.1, { scale: v3(0.6, 0.6, 1) }).to(0.1, { scale: v3(0.5, 0.5, 1) }).start();
        this.scheduleOnce(() => this.setting.setPosition(v3()), 0.1);
    }
    /**返回主页 */
    BackToMainScene() {
        director.loadScene(`MainScene`);
    }
    /**重新加载关卡 */
    ReloadLevel(e: EventTouch, mes?: string) {
        if (mes) {
            DataManager.Instance.curLevel++;
        }
        if (DataManager.Instance.curLevel >= DataManager.Instance.nodeLens) {
            DataManager.Instance.nodeLens++;
            try {
                wx.setUserCloudStorage({
                    KVDataList: [{ key: `s`, value: `${DataManager.Instance.nodeLens}` }],
                    success: (res) => {
                        console.log('成功',res);
                    },
                    fail: (res) => {
                        console.log('失败',res);
                    }
                })
            } catch (error) {
                console.log('error',error);
            }
        }
        if (DataManager.Instance.LevelArr[DataManager.Instance.curLevel]) {
            director.loadScene('PlayScene');
        }
        else {
            console.log('尽头 :>> ');
        }
    }
    /**更新道具数量 */
    updatePropNum()
    {
        this.propNum.forEach((e,i)=>
        {
            e.string=`${DataManager.Instance.propArr[i][0]}`;
        })
    }
}

